package net.apexes.commons.ormlite;

import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.misc.TransactionManager;
import com.j256.ormlite.support.ConnectionSource;

import java.sql.SQLException;
import java.util.concurrent.Callable;

/**
 * @author <a href=mailto:hedyn@foxmail.com>HeDYn</a>
 */
public final class DatabaseUtil {

    public static <E> E callInTransaction(ConnectionSource conn, Callable<E> callable) throws SQLException {
        return TransactionManager.callInTransaction(conn, callable);
    }

    public static <T, ID>  Dao<T, ID> dao(ConnectionSource conn, Table<T> table) throws SQLException {
        return new TableDaoImpl<>(conn, table);
    }

    /**
     * @author <a href=mailto:hedyn@foxmail.com>HeDYn</a>
     */
    private static class TableDaoImpl<T, ID> extends BaseDaoImpl<T, ID> {

        protected TableDaoImpl(ConnectionSource conn, Table<T> table) throws SQLException {
            super(conn, table.config());
            this.setObjectFactory(table.objectFactory());
        }
    }
}
